package com.ruoyi.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.system.domain.vo.TemplateData;
import com.ruoyi.system.domain.vo.WxMssVO;
import com.ruoyi.system.service.XcxPublicService;
import com.ruoyi.system.util.HttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.common.core.web.domain.AjaxResult.success;

@Api(tags = "小程序公共接口")
@RestController
@RequestMapping("/xcxpublic")
public class XcxPublicController {

    @Autowired
    RedisService redisService;

    @Autowired
    XcxPublicService xcxPublicService;

    // AppId
//    private static String appid="wx9aa699b4ead5f310";
    private static String appid = "wx48e8651ec3b15170";

    // 小程序密钥
//    private static String secret="52c3e20dc34c0e2b109ef08d5d7507a1";
    private static String secret = "84040cce47cb097ed50f6e77a036b0f7";

    // 地址
    // openid 地址
    private  static final  String opidurl="https://api.weixin.qq.com/sns/jscode2session";
    // access_token 地址
    private  static final  String access_tokenurl="https://api.weixin.qq.com/cgi-bin/token";
    // 订阅消息推送 地址
    private static final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

    // 企业微信 access_token 地址
    private static  final  String QY_URL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx71ef5f8f5e4cf22f&corpsecret=5re3CnQXxlV3PJzdFbgmOVb8ksXJnFqhb-u6BVswTCY";

    // 企业微信 通知发送 地址
    private  static  final  String QY_PUSH_URL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";


    @InnerAuth
    @ApiOperation(notes = "", value = "返回获取企业微信 access_token")
    @PostMapping("/qy_access_token")
    public AjaxResult qy_access_token() {
        String resultStr="";
//        Map<String, String> params = new HashMap<>();
//        resultStr = HttpClient.sendGet(QY_URL,params);
//        Long date=new Date().getTime();
//        JSONObject jo=JSONObject.parseObject(resultStr);
//        System.out.println(jo);
//        redisService.setCacheObject("qy_access_tokenurl",jo.get("access_token")+","+date);
//        resultStr=jo.get("access_token").toString();
        //        读取 检查 Redis access_tokenurl
        if(redisService.hasKey("qy_access_tokenurl")){
            String buffs=redisService.getCacheObject("qy_access_tokenurl");
            String[] rlist=buffs.split(",");
            Long s = (System.currentTimeMillis() -  Long.parseLong(rlist[1])) / (1000 * 60);
            System.out.println("存在"+s+"分组");
            System.out.println(buffs);
            if(s>100){
                Map<String, String> params = new HashMap<>();
                resultStr = HttpClient.sendGet(QY_URL,params);
                Long date=new Date().getTime();
                JSONObject jo=JSONObject.parseObject(resultStr);
                redisService.setCacheObject("qy_access_tokenurl",jo.get("access_token")+","+date);
                resultStr=jo.get("access_token").toString();
            }else{
                resultStr=rlist[0];
            }
        }else{
            System.out.println("不存在");
            Map<String, String> params = new HashMap<>();
            resultStr = HttpClient.sendGet(QY_URL,params);
            Long date=new Date().getTime();
            JSONObject jo=JSONObject.parseObject(resultStr);
            System.out.println(jo);
            redisService.setCacheObject("qy_access_tokenurl",jo.get("access_token")+","+date);
            resultStr=jo.get("access_token").toString();
        }
        return success(resultStr);
    }

//    @InnerAuth
    @ApiOperation(notes = "", value = "发送企业微信 小程序 消息")
    @PostMapping("/qywxxcx_msg_push")
    public String qywxxcx_msg_push(@RequestBody JSONObject info) {
        Map<String,Object> data=info;
        RestTemplate restTemplate = new RestTemplate();
        qy_access_token();
        String buffs=redisService.getCacheObject("qy_access_tokenurl");
        String[] rlist=buffs.split(",");
        String url =  QY_PUSH_URL+rlist[0];
        //拼接推送的模版
        String pr="{\n" +
                "  \"touser\": \""+data.get("to").toString()+"\",\n" +
                "  \"msgtype\": \"miniprogram_notice\",\n" +
                "  \"agentid\": 1000004,\n" +
                "  \"miniprogram_notice\": {\n" +
                "    \"appid\": \"wx48e8651ec3b15170\",\n" +
                "    \"page\": \""+data.get("url").toString()+"\",\n" +
                "    \"title\": \"单据待签核通知\",\n" +
                "    \"description\": \"Sign off on the notification\",\n" +
                "    \"content_item\": [{\n" +
                "        \"key\": \"签核\",\n" +
                "        \"value\": \""+data.get("type").toString()+"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"key\": \"申请人\",\n" +
                "        \"value\": \""+data.get("username").toString()+"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"key\": \"部门\",\n" +
                "        \"value\": \""+data.get("deptname").toString()+"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"key\": \"申请时间\",\n" +
                "        \"value\": \""+data.get("creatime").toString()+"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"key\": \"签核状态\",\n" +
                "        \"value\": \"待您签核\"\n" +
                "      }\n" +
                "    ]\n" +
                "  },\n" +
                "  \"safe\": 0,\n" +
                "  \"enable_id_trans\": 0,\n" +
                "  \"enable_duplicate_check\": 0\n" +
                "}";
        JSONObject jo=JSONObject.parseObject(pr);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,jo,String.class);
        return responseEntity.getBody();
    }



    @ApiOperation(notes = "", value = "返回获取openid地址")
    @PostMapping("/openid_url")
    public AjaxResult openid_url(@RequestBody String code) {
        System.out.println(code);
        Map<String, String> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        params.put("js_code",code);
        params.put("grant_type", "authorization_code");
        String resultStr = HttpClient.sendGet(opidurl,params);
        System.out.println(resultStr);
        return success(resultStr);
    }


    @ApiOperation(notes = "", value = "返回获取access_token地址")
    @PostMapping("/get_access_token")
    public AjaxResult get_access_token(){
        String resultStr="";
        //        读取 检查 Redis access_tokenurl
        if(redisService.hasKey("access_tokenurl")){
            String buffs=redisService.getCacheObject("access_tokenurl");
            String[] rlist=buffs.split(",");
            Long s = (System.currentTimeMillis() -  Long.parseLong(rlist[1])) / (1000 * 60);
            System.out.println("存在"+s+"分钟");
            if(s>100){
                Map<String, String> params = new HashMap<>();
                params.put("appid",appid);
                params.put("secret",secret);
                params.put("grant_type", "client_credential");
                resultStr = HttpClient.sendGet(access_tokenurl,params);
                Long date=new Date().getTime();
                JSONObject jo=JSONObject.parseObject(resultStr);
                redisService.setCacheObject("access_tokenurl",jo.get("access_token")+","+date);
                resultStr=jo.get("access_token").toString();
            }else{
                resultStr=rlist[0];
            }
        }else{
            System.out.println("不存在");
            Map<String, String> params = new HashMap<>();
            params.put("appid",appid);
            params.put("secret",secret);
            params.put("grant_type", "client_credential");
            resultStr = HttpClient.sendGet(access_tokenurl,params);
            Long date=new Date().getTime();
            JSONObject jo=JSONObject.parseObject(resultStr);
            redisService.setCacheObject("access_tokenurl",jo.get("access_token")+","+date);
            resultStr=jo.get("access_token").toString();
        }
        System.out.println("access_token"+resultStr);
        return success(resultStr);
    }

    @ApiOperation(notes = "", value = "发送订阅消息")
    @PostMapping("/xcx_msg_push")
    public String xcx_msg_push(@RequestBody JSONObject info) {
        Map<String,Object> data=info.getJSONObject("xcx");
        RestTemplate restTemplate = new RestTemplate();
        get_access_token();
        String buffs=redisService.getCacheObject("access_tokenurl");
        String[] rlist=buffs.split(",");
        String url =  SEND_INFO_URL+rlist[0];
        //拼接推送的模版
        WxMssVO wxMssVo = new WxMssVO();
        wxMssVo.setTouser(data.get("openid").toString());//用户的openId
        wxMssVo.setTemplate_id(data.get("templateid").toString());//订阅消息模板id
        wxMssVo.setPage("pages/notice/notice");
        Map<String, TemplateData> m = new HashMap<>(5);
        TemplateData t1=new TemplateData();
        t1.setValue(data.get("thing3").toString());
        m.put("thing3", t1);
        TemplateData t2=new TemplateData();
        t2.setValue(data.get("phrase4").toString());
        m.put("phrase4", t2);
        TemplateData t3=new TemplateData();
        t3.setValue(data.get("thing5").toString());
        m.put("thing5", t3);
        TemplateData t4=new TemplateData();
        t4.setValue(data.get("time7").toString());
        m.put("time7", t4);
        wxMssVo.setData(m);
//        System.out.println("wxMssVo=================>"+wxMssVo);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }


    @ApiOperation(notes = "", value = "统计数据")
    @PostMapping("/statistics_list")
    public AjaxResult statistics_list(){
        return  success(xcxPublicService.statistics_list());
    }

}
